/*
 * InterruptableInputStream.java
 *
 * Created on December 6, 2006, 8:44 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.umn.cs5115.scheduler;

import java.io.IOException;
import java.io.InputStream;

/**
 * Wraps any normal input stream, but starts throwing IO exceptions whenever
 * possible if the thread gets interrupted.
 * @author grant
 */
public class InterruptableInputStream extends InputStream
{
    private InputStream actualStream;
    
    /** Creates a new instance of InterruptableInputStream */
    public InterruptableInputStream(InputStream actualStream)
    {
        this.actualStream = actualStream;
    }

    public int read() throws IOException
    {
        throwIOExceptionIfInterrupted();
        int value = actualStream.read();
        throwIOExceptionIfInterrupted();
        return value;
    }
    
    public int available() throws IOException
    {
        throwIOExceptionIfInterrupted();
        int available = actualStream.available();
        throwIOExceptionIfInterrupted();
        return available;
    }
    
    /** Closes this input stream and releases any system resources associated with the stream. */
    public void close() throws IOException
    {
        actualStream.close();
        throwIOExceptionIfInterrupted();
    }
          
    public void mark(int readlimit)
    {
        actualStream.mark(readlimit);
    }
    
    public boolean markSupported()
    {
        return actualStream.markSupported();
    }
    
    public void reset() throws IOException
    {
        throwIOExceptionIfInterrupted();
        actualStream.reset();
        throwIOExceptionIfInterrupted();
    }
    
    public long skip(long n) throws IOException
    {
        throwIOExceptionIfInterrupted();
        long skipped = actualStream.skip(n);
        throwIOExceptionIfInterrupted();
        return skipped;
    }
    
    private void throwIOExceptionIfInterrupted() throws IOException
    {
        if (Thread.currentThread().isInterrupted())
        {
            actualStream.close();
            throw new IOException("Input interrupted.");
        }
    }
}
